new Vue({
  el: "#app",
  data() {
    return {
      value1: "",
      radio: "1",
      // activeNames: ["1"],
      dj: {},
      fh: {},
      dh: {},
      wk: {},

      options: [
        {
          value: "公斤",
          label: "公斤",
        },
        {
          value: "箱",
          label: "箱",
        },
        {
          value: "千克",
          label: "千克",
        },
        {
          value: "克",
          label: "克",
        },
        {
          value: "袋",
          label: "袋",
        },
        {
          value: "吨",
          label: "吨",
        },
      ],
      use: decodeURI($.cookie("use")),
      iJSONArray_Variety: [],
      iJSONArray_VarietyGrade: [],
      VarietyName: "",
      form: {},
      rules: {
        VarietyName: [
          // { required: true, message: "请输入食用菌品种", trigger: "blur" },
        ],
      },
      loading: false,
      is_VarietyId: "",
      is_VarietyGrade_Id: "",
      is_Unit: "",
    };
  },
  mounted() {
    // console.log(this.use);
    this.getVarietyList();
    // this.getRequesterID();
    // const ls_username = sessionStorage.getItem("username");
    // console.log(ls_username);

    // const username = new URLSearchParams(window.location.search);

    // const myParam = username.get("username");
  },
  methods: {
    czd() {
      const _this = this;
      $.ajax({
        headers: {
          AccessToken: $.cookie("token"), //会将数据转换为query string
        },
        url: "https://service.kdddy.cn/donghui/generalBusiness/generalQueryByTableName",
        type: "POST",
        data: {
          Data: "business_PaymentNode", //表名
          Condition: "Row_Status='0'",
        },
        success: function (Result) {
          console.log(Result);
          for (let i = 0; i < Result.length; i++) {
            if (Result[i].node_name == "定金") {
              _this.dj.payment_node_id = Result[i].payment_node_id;
            } else if (Result[i].node_name == "发货") {
              _this.fh.payment_node_id = Result[i].payment_node_id;
            } else if (Result[i].node_name == "到货") {
              _this.dh.payment_node_id = Result[i].payment_node_id;
            } else {
              _this.wk.payment_node_id = Result[i].payment_node_id;
            }
          }
          _this.tj();
        },
        complete: function (XMLHttpRequest) {},
        dataType: "json",
      });
    },
    tj() {
      // return;
      console.log(this.is_VarietyId);
      console.log(this.is_VarietyGrade_Id);
      console.log(this.form.Origin);
      console.log(this.form.UnitPrice);
      console.log(this.form.QuotationDate);
      console.log(this.form.SupplyQuantity);
      console.log(this.is_Unit);
      console.log(this.form.Self_Pickup_Location);

      if (this.is_VarietyId == "") {
        this.$message.error("请选择食用菌品种");
        return;
      }
      if (this.is_VarietyGrade_Id == "") {
        this.$message.error("请选择等级");
        return;
      }
      if (this.form.Origin == undefined) {
        this.$message.error("请输入产地");
        return;
      }
      if (this.form.UnitPrice == undefined) {
        this.$message.error("请输入单价");
        return;
      }
      if (this.form.QuotationDate == undefined) {
        this.$message.error("请选择日期");
        return;
      }
      if (this.form.SupplyQuantity == undefined) {
        this.$message.error("请选择供应量");
        return;
      }
      if (this.is_Unit == "") {
        this.$message.error("请选择供应单位");
        return;
      }
      if (this.form.Self_Pickup_Location == undefined) {
        this.$message.error("请输入提货点/发货地");
        return;
      }
      const djAmount = parseFloat(this.dj.dje) || 0;
      const fhAmount = parseFloat(this.fh.fhe) || 0;
      const dhAmount = parseFloat(this.dh.dhe) || 0;
      const wkAmount = parseFloat(this.wk.wke) || 0;
      const total = djAmount + fhAmount + dhAmount + wkAmount;
      console.log(total);
      if (total == 0) {
        this.$message.error("请输入收款方式");
        return;
      } else if (total > 100) {
        this.$message.error("定金、发货、到货、尾款的额度总和不能超过 100");
        this.dj.dje = "";
        this.fh.fhe = "";
        this.dh.dhe = "";
        this.wk.wke = "";
        return;
      } else if (total < 100) {
        this.$message.error("定金、发货、到货、尾款的额度总和不能小于 100");
        this.dj.dje = "";
        this.fh.fhe = "";
        this.dh.dhe = "";
        this.wk.wke = "";
        return;
      }

      // 当只输入一个额度比时，检查是否不小于 100
      const amounts = [djAmount, fhAmount, dhAmount, wkAmount];
      const nonZeroAmounts = amounts.filter((amount) => amount > 0);
      if (nonZeroAmounts.length === 1 && nonZeroAmounts[0] < 100) {
        this.$message.error("当只输入一个额度比时，该额度比必须不小于 100");
        return;
      }

      const _this = this;
      for (let i = 0; i < _this.options.length; i++) {
        if (_this.is_Unit == _this.options[i].value) {
          _this.is_Unit = _this.options[i].label;
        }
      }
      _this.form.Unit = _this.is_Unit;
      _this.form.Acceptance_Status = "1";
      _this.form.VarietyID = _this.is_VarietyId;
      _this.form.GradeID = _this.is_VarietyGrade_Id;
      _this.form.RemainingQuantity = _this.form.SupplyQuantity;
      _this.form.OccupiedQuantity = 0;
      let Enterprise_Info_SerialNumber = sessionStorage.getItem(
        "Enterprise_Info_SerialNumber"
      );
      _this.form.Provider = Enterprise_Info_SerialNumber;
      _this.form.ConfirmationStatus = "0";

      if (_this.radio == "1") {
        _this.form.Shipping_Method = "面对面自提";
      } else {
        _this.form.Shipping_Method = "运输";
      }
      // 定义付款节点数组，包含每个节点对应的额度比字段、日期字段和节点对象
      const paymentNodes = [
        { ratioField: "dje", dateField: "djs", node: this.dj },
        { ratioField: "fhe", dateField: "fhs", node: this.fh },
        { ratioField: "dhe", dateField: "dhs", node: this.dh },
        { ratioField: "wke", dateField: "wks", node: this.wk },
      ];

      // 遍历付款节点数组
      paymentNodes.forEach(({ ratioField, dateField, node }) => {
        // 将额度比字段的值转换为浮点数
        const paymentRatio = parseFloat(node[ratioField]);
        // 检查额度比是否为有效数字且大于 0，同时日期字段是否为 undefined
        if (
          !isNaN(paymentRatio) &&
          paymentRatio > 0 &&
          node[dateField] === undefined
        ) {
          // 将日期字段的值设置为 '0'
          node[dateField] = "0";
        }
      });

      _this.dj.Payment_Ratio = parseInt(_this.dj.dje);
      _this.dj.Expected_Payment_Date = _this.dj.djs;
      _this.dj.actual_payment_amount = "0";
      _this.dj.payment_status = "待付款";

      _this.fh.Payment_Ratio = parseInt(_this.fh.fhe);
      _this.fh.Expected_Payment_Date = _this.fh.fhs;
      _this.fh.actual_payment_amount = "0";
      _this.fh.payment_status = "待付款";

      _this.dh.Payment_Ratio = parseInt(_this.dh.dhe);
      _this.dh.Expected_Payment_Date = _this.dh.dhs;
      _this.dh.actual_payment_amount = "0";
      _this.dh.payment_status = "待付款";

      _this.wk.Payment_Ratio = parseInt(_this.wk.wke);
      _this.wk.Expected_Payment_Date = _this.wk.wks;
      _this.wk.actual_payment_amount = "0";
      _this.wk.payment_status = "待付款";

      console.log(_this.fkzz, "_this.fkzz");
      let lJSONArray_fkzq = new Array();
      lJSONArray_fkzq.push(_this.dj, _this.fh, _this.dh, _this.wk);
      for (let i = 0; i < lJSONArray_fkzq.length; i++) {
        if (isNaN(lJSONArray_fkzq[i].Payment_Ratio)) {
          lJSONArray_fkzq[i].Payment_Ratio = "";
        }
      }
      lJSONArray_fkzq.forEach((element) => {
        console.log(element);
        if (element.Payment_Ratio == 0) {
          element.Payment_Ratio = "";
        }
        if (
          !element.Payment_Ratio &&
          element.Expected_Payment_Date == undefined
        ) {
          element.Expected_Payment_Date = 0;
        }
      });
      console.log(lJSONArray_fkzq);

      //子表表名
      let lJSONObject_base_QuotationPaymentDetail = new Object();
      lJSONObject_base_QuotationPaymentDetail.base_QuotationPaymentDetail =
        lJSONArray_fkzq; //换表
      // return;
      // lJSONObject_base_QuotationPaymentDetail.Children =
      //   lJSONObject_base_QuotationPaymentDetail;
      // let lJSONObject_business_PaymentNode = new Object();
      // lJSONObject_base_QuotationPaymentDetail.business_PaymentNode =
      //   lJSONArray_fkzq;

      _this.form.Children = lJSONObject_base_QuotationPaymentDetail;

      let lJSONArray_business_Quotation = new Array();
      lJSONArray_business_Quotation.push(_this.form);

      console.log(lJSONArray_business_Quotation, "1111111111");

      let lJSONObject_business_Quotation1 = new Object();
      lJSONObject_business_Quotation1.business_Quotation =
        lJSONArray_business_Quotation;
      console.log(lJSONObject_business_Quotation1, "222222222222");

      // 判断 PaymentMethod
      let hasSingleFullPayment = false;
      for (let i = 0; i < lJSONArray_fkzq.length; i++) {
        const paymentRatio = parseFloat(lJSONArray_fkzq[i].Payment_Ratio) || 0;
        if (paymentRatio === 100) {
          let otherRatiosSum = 0;
          for (let j = 0; j < lJSONArray_fkzq.length; j++) {
            if (j !== i) {
              otherRatiosSum +=
                parseFloat(lJSONArray_fkzq[j].Payment_Ratio) || 0;
            }
          }
          if (otherRatiosSum === 0) {
            hasSingleFullPayment = true;
            break;
          }
        }
      }

      lJSONArray_business_Quotation[0].PaymentMethod = hasSingleFullPayment
        ? "一次性付款"
        : "阶段付款";

      // console.log(_this.form, "_this.form");

      // let lArray = new Array();
      // lArray.push(_this.form);
      // let lJSONObject_business_PurchaseRequest = new Object();
      // lJSONObject_business_PurchaseRequest.business_Quotation = lArray;

      let lJSONObject_DataSet = new Object();
      lJSONObject_DataSet.Add = lJSONObject_business_Quotation1;
      console.log(lJSONObject_DataSet, "lJSONObject_DataSet");

      // return;
      $.ajax({
        headers: {
          AccessToken: $.cookie("token"), //会将数据转换为query string
        },
        url: "https://service.kdddy.cn/donghui/clientOperation/generalSaveForClient",
        type: "POST",
        data: {
          Data: JSON.stringify(lJSONObject_DataSet),
        },
        success: function (Result) {
          console.log(Result);
          if (Result.Status === "success") {
            _this.$message.success("提交成功");
            window.history.go(-1);
          } else {
            _this.$message.error("提交失败，请稍后再试");
          }
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
        },
        dataType: "json",
      });
    },

    //查询企业信息和个人信息
    // getRequesterID() {
    //   let User_Number = sessionStorage.getItem("User_Number");
    //   console.log(User_Number);
    //   // return;
    //   const _this = this;
    //   $.ajax({
    //     headers: {
    //       AccessToken: $.cookie("token"), //会将数据转换为query string
    //     },
    //     url: "https://service.kdddy.cn/donghuiForRequest/selectByData/selectEnterpriseID",
    //     type: "get",
    //     data: {
    //       Data: User_Number,
    //     },
    //     success: function (Result) {
    //       console.log(Result);
    //       console.log(Result.Data[0]);
    //       // _this.form.RequesterID = Result.Data[0].Enterprise_Info_SerialNumber;
    //       // console.log(Result.Data[0].Enterprise_Info_SerialNumber);

    //       _this.submitForm();
    //     },
    //     complete: function (XMLHttpRequest) {
    //       requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
    //     },
    //     dataType: "json",
    //   });
    // },
    submitForm() {
      console.log(this.value1);
      this.form.PublishDate = this.value1[0];
      this.form.EndDate = this.value1[1];
      console.log(this.form);
      // return;
      const _this = this;
      for (let i = 0; i < _this.options.length; i++) {
        console.log(_this.options[i].value);

        if (_this.is_Unit == _this.options[i].value) {
          _this.is_Unit = _this.options[i].label;
        }
      }
      _this.form.Unit = _this.is_Unit;
      _this.form.VarietyID = _this.is_VarietyId;
      _this.form.GradeID = _this.is_VarietyGrade_Id;
      let Enterprise_Info_SerialNumber = sessionStorage.getItem(
        "Enterprise_Info_SerialNumber"
      );
      _this.form.RequesterID = Enterprise_Info_SerialNumber;
      _this.form.CompletionStatus = "0";
      _this.form.Acceptance_Status = "0";
      console.log(_this.form, "_this.form");

      let lArray = new Array();
      lArray.push(_this.form);
      let lJSONObject_business_PurchaseRequest = new Object();
      lJSONObject_business_PurchaseRequest.business_PurchaseRequest = lArray;

      let lJSONObject_DataSet = new Object();
      lJSONObject_DataSet.Add = lJSONObject_business_PurchaseRequest;

      console.log(lJSONObject_DataSet, "lJSONObject_DataSet");
      // return;
      $.ajax({
        headers: {
          AccessToken: $.cookie("token"), //会将数据转换为query string
        },
        url: "https://service.kdddy.cn/donghui/generalBusiness/generalSave",
        type: "POST",
        data: {
          Data: JSON.stringify(lJSONObject_DataSet),
        },
        success: function (Result) {
          console.log(Result);
          if (Result.Status === "success") {
            _this.$message.success("提交成功");
            window.history.go(-1);
          } else {
            _this.$message.error("提交失败，请稍后再试");
          }
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
        },
        dataType: "json",
      });
    },
    handleChange(value) {
      console.log(value, "value");

      // return;
      const _this = this;
      $.ajax({
        headers: {
          AccessToken: $.cookie("token"), //会将数据转换为query string
        },
        url: "https://service.kdddy.cn/donghui/generalBusiness/generalQueryByTableName",
        type: "POST",
        data: {
          Data: "base_EdibleMushroomGrade",
          Condition:
            "Row_Status='0' AND VarietyID='" + _this.is_VarietyId + "'",
        },
        success: function (Result) {
          // _this.tableData = Result.Rows;
          _this.iJSONArray_VarietyGrade = new Array(); //清空数组中原有值
          _this.iJSONArray_VarietyGrade = Result;
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
        },
        dataType: "json",
      });
    },
    getVarietyList() {
      const _this = this;
      $.ajax({
        headers: {
          AccessToken: $.cookie("token"), //会将数据转换为query string
        },
        url: "https://service.kdddy.cn/donghui/generalBusiness/generalQueryByTableName",
        type: "POST",
        data: {
          Data: "base_EdibleMushroomVariety",
          Condition: "Row_Status='0'",
        },
        success: function (Result) {
          console.log(Result);

          // _this.tableData = Result.Rows;
          _this.iJSONArray_Variety = Result;
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
        },
        dataType: "json",
      });
    },
  },
});
